package com.sheepone.util.time;


import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAccessor;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author Miss.杨
 */
public class TimeUtil {
    private TimeUtil() {
    }


    public static Date localDateTimeToDate(LocalDateTime localDateTime) {
        return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
    }

    /**
     * 获取指定时间之前最近的一个整10秒时刻。
     */
    public static LocalDateTime lastWholeTenSeconds(LocalDateTime dateTime) {
        int remainder = dateTime.getSecond() % 10;
        if (remainder == 0) {
            // 如果已经是整10秒,则返回当前时间
            return dateTime;
        } else {
            // 否则，减去余下的秒数
            return dateTime.plusSeconds(-remainder);
        }
    }

    /**
     * 获取指定时间之前最近的一个整5秒时刻。
     */
    public static LocalDateTime lastWholeFiveSeconds(LocalDateTime dateTime) {
        int second = dateTime.getSecond();
        int remainder = second % 5;
        if (second % 10 == 0) {
            remainder = 5;
        } else if (remainder == 0) {
            // 如果已经是整10秒,则返回当前时间
            return dateTime;
        }
        // 否则，减去余下的秒数
        return dateTime.plusSeconds(-remainder);
    }

    public static <T> List<T> selectEveryFixedTimes(List<T> list, long seconds) {
        if (list.isEmpty()) {
            return null;
        }
        if (list.get(0) instanceof SecondStampHolder) {
            ArrayList<T> holders = new ArrayList<>();
            holders.add(list.get(0));
            int cnt = 0;
            for (int i = 1; i < list.size(); i++) {
                SecondStampHolder p = (SecondStampHolder) list.get(i);
                SecondStampHolder t = (SecondStampHolder) holders.get(cnt);
                if (p.getSecondStamp() - t.getSecondStamp() >= seconds) {
                    holders.add(list.get(i));
                    cnt++;
                }
            }
            return holders;
        }
        throw new RuntimeException("list‘s component type must extended SecondStampHolder");
    }

}
